package com.example.backend.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import com.example.backend.annotation.RateLimit;
import com.example.backend.entity.Image;
import com.example.backend.mapper.ImageMapper;
import com.example.backend.util.Result;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/image")
public class ImageController {

    private final ImageMapper imageMapper;


    private final OSS ossClient;

    @Value("${aliyun.oss.bucket-name}")
    private String bucketName;

//    @Value("${aliyun.oss.endpoint}")
//    private String endpoint;

    ImageController(ImageMapper imageMapper, OSS ossClient) {
        this.imageMapper = imageMapper;
        this.ossClient = ossClient;
    }


    // 上传图片（使用私有存储桶）
    @RateLimit
    @PostMapping("/upload")
    public Result<Object> insert_image(
            @RequestParam("file") MultipartFile file,
            @RequestParam("pid") String pid
    ) {
        try {
            if (file.isEmpty()) {
                return Result.error("400", "File is empty");
            }

            // 生成唯一文件名
            String fileName = UUID.randomUUID() + "-" + file.getOriginalFilename();
            String filePath = "images/" + fileName;

            // 上传到私有存储桶
            ossClient.putObject(bucketName, filePath, file.getInputStream());

            // 保存对象路径到数据库（不是完整URL）
            imageMapper.insert_image(file.getOriginalFilename(), pid, filePath);

            return Result.success();
        } catch (Exception e) {
            // 检查OSS异常
            if (e instanceof OSSException oe) {
                String errorMsg = String.format(
                        "OSS Error: %s \nRequestID: %s \nHostID: %s",
                        oe.getErrorMessage(),
                        oe.getRequestId(),
                        oe.getHostId()
                );
                return Result.error("500", errorMsg);
            }
            return Result.error("500", e.getMessage());
        }
    }

    // 获取图片（返回预签名URL）
    @RateLimit
    @GetMapping("/get/{id}")
    public Result<List<Image>> select_image_pid(@PathVariable String id) {
        try {
            List<Image> images = imageMapper.select_image_pid(id);
            if (images != null && !images.isEmpty()) {
                // 为每个图片生成预签名URL
                for (Image image : images) {
                    String filePath = image.getUrl(); // 这里存储的是OSS对象路径
                    String signedUrl = generatePresignedUrl(filePath);
                    image.setSignedUrl(signedUrl); // 添加临时访问URL
                }
                return Result.success(images);
            }
            return Result.error("404", "Image not found");
        } catch (Exception e) {
            return Result.error("500", e.getMessage());
        }
    }

    // 生成预签名URL（有效期1小时）
    private String generatePresignedUrl(String objectPath) {
        // 设置URL过期时间
        Date expiration = new Date(System.currentTimeMillis() + TimeUnit.HOURS.toMillis(1));

        // 创建请求
        GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectPath);
        request.setExpiration(expiration);

        // 生成URL
        URL url = ossClient.generatePresignedUrl(request);
        return url.toString();
    }
}
